package com.chonglie;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class BroadcastReceiverActivity extends Activity {

	public static final String ACTION_1 = "action_1";
	public static final String ACTION_2 = "action_2";
	public static final String ACTION_3 = "action_3";

	private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			Toast.makeText(context,
					getString(R.string.RECEIVER_MSG_DYNAMIC) + action, 1000)
					.show();
		}
	};

	private BroadcastReceiver sysReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 如果捕捉到的action是ACTION_BATTERY_CHANGED
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)
					|| ACTION_3.equals(action)) {

				Toast.makeText(context,
						getString(R.string.RECEIVER_MSG_SYS) + action, 1000)
						.show();

				Bundle b = intent.getExtras();
				if (b != null) {
					Object[] lstName = b.keySet().toArray();

					for (int i = 0; i < lstName.length; i++) {
						String keyName = lstName[i].toString();
						Log.e("sysReceiver",
								keyName + ":" + String.valueOf(b.get(keyName)));
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.broadcast_receiver);
		registerReceiver(dynamicReceiver, new IntentFilter(ACTION_1));

	}

	public void sendToDynamic(View view) {
		Intent intent = new Intent(ACTION_1);
		sendBroadcast(intent);
	}

	public void sendToStatic(View view) {
		Intent intent = new Intent(ACTION_2);
		sendBroadcast(intent);
	}

	public void sendToSys(View view) {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_BATTERY_CHANGED);
		filter.addAction(ACTION_3);
		registerReceiver(sysReceiver, filter);

		Intent intent = new Intent(ACTION_3);
		intent.putExtra("name", "zhangsan");
		intent.putExtra("age", 10);
		sendBroadcast(intent);
	}
}
